package cst.a225xm.startproject225.model;

import cst.a225xm.startproject225.bean.WeatherInfo;
import cst.a225xm.startproject225.bean.WeatherResult;
import cst.a225xm.startproject225.iface.WeatherIface;
import cst.a225xm.startproject225.listener.WeatherListener;
import cst.a225xm.startproject225.service.WeatherService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Admin on 2017/5/10.
 */

public class WeatherModel implements WeatherIface{
    private Retrofit retrofit;
    private static final String BASE_URL="http://www.weather.com.cn/";

    public WeatherModel(){
        retrofit=new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    @Override
    public void getWeather(String citynumber, final WeatherListener listener) {
        WeatherService service=retrofit.create(WeatherService.class);
        Call<WeatherResult> call=service.getResult(citynumber);
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if(response.isSuccessful()&&response.body()!=null){
                    listener.onResponse(response.body().getWeatherInfo());
                }
                else {
                    listener.onFail("error");
                }
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listener.onFail(t.toString());
            }
        });
    }
}
